package rs.mbs2.epics.server.servlet;

import java.io.IOException;
import java.util.Date;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import rs.mbs2.epics.server.entity.Photo;
import rs.mbs2.epics.server.entity.User;
import rs.mbs2.epics.server.session.dao.localinterface.PhotoDaoLocal;
import rs.mbs2.epics.server.session.dao.localinterface.UserDaoLocal;

@SuppressWarnings("serial")
public class AddFavoritePhotoController extends HttpServlet {
	
	private static Logger log = Logger.getLogger(AddFavoritePhotoController.class);
	
	@EJB
	PhotoDaoLocal photoDao;
	
	@EJB
	UserDaoLocal userDao;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		int photoId = Integer.parseInt(request.getParameter("photoId"));
		Photo photo = photoDao.findById(photoId);
		
		User userSession = (User)request.getSession().getAttribute("user");
		User user = userDao.findById(userSession.getId());
		
		user.getFavouriteAlbum().getPhotos().add(photo);
		userDao.merge(user);
		
		log.info(new Date() + ": Korisnik[id]: " + user.getId() + "obelezio sliku[id]:" + photoId + " kao omiljenu.");		

		
		//response.sendRedirect("./ViewPhotoController?id=" + photoId);
		
		request.getRequestDispatcher("/ViewPhotoController?id=" + photoId).forward(request, response);
		
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
